package com.atguigu.guli.service.trade.service.impl;

import com.atguigu.guli.common.base.result.ResultCodeEnum;
import com.atguigu.guli.common.base.util.ExceptionUtils;
import com.atguigu.guli.common.base.util.HttpClientUtils;
import com.atguigu.guli.service.base.exception.MyException;
import com.atguigu.guli.service.trade.entity.Order;
import com.atguigu.guli.service.trade.service.OrderService;
import com.atguigu.guli.service.trade.service.WeixinPayService;
import com.atguigu.guli.service.trade.util.WeixinPayProperties;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.generic.InstructionConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zero
 * @desc
 * @create 2020/5/31
 */
@Service
@Slf4j
public class WeixinPayServiceImpl implements WeixinPayService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WeixinPayProperties weixinPayProperties;

    /**
     * 根据订单号和远程地址生成付款二维码
     *
     * @param orderNo    订单号
     * @param remoteAddr 远程地址
     * @return 返回
     */
    @Override
    public Map<String, Object> createNative(String orderNo, String remoteAddr) {

        // 获取订单信息
        Order order = orderService.getOrderByOrderNo(orderNo);
        // 调用微信API：统一下单api

        // 1、创建HTTPClient
        HttpClientUtils client = new HttpClientUtils("https://api.mch.weixin.qq.com/pay/unifiedorder");
        // 封装下单参数
        HashMap<String, String> params = new HashMap<>(9);
        params.put("appid ", weixinPayProperties.getAppId());
        params.put("mch_id", weixinPayProperties.getPartner());
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body", order.getCourseTitle());
        params.put("out_trade_no", orderNo);

        // 订单金额，单位为： 分
        Object key;
        String totalFee = String.valueOf(order.getTotalFee().intValue());
        params.put("total_fee", totalFee);
        params.put("spbill_create_ip", remoteAddr);
        params.put("notify_url", weixinPayProperties.getNotifyUrl());
        params.put("trade_type", "NATIVE");

        //将参数转换成xml字符串格式：生成带有签名的xml格式字符串
        try {
            String xmlParams = WXPayUtil.generateSignedXml(params, weixinPayProperties.getPartnerKey());
            client.setXmlParam(xmlParams);
            client.setHttps(true);
            client.post();
            String resultXml = client.getContent();
            // 将获取的响应转成Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(resultXml);
            // 处理响应数据
            String returnCode = resultMap.get("return_code");
            String resultCode = resultMap.get("result_code");
            if("FAIL".equals(returnCode) || "FAIL".equals(resultCode)) {
                log.error("微信支付统一下单错误 - "
                        + "return_code: " + returnCode
                        + "return_msg: " + resultMap.get("return_msg")
                        + "result_code: " + resultCode
                        + "err_code: " + resultMap.get("err_code")
                        + "err_code_des: " + resultMap.get("err_code_des"));

                throw new MyException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
            }

            // 组装返回的参数
            HashMap<String, Object> returnMap = new HashMap<>(5);
            returnMap.put("result_code", resultMap.get("result_code"));
            returnMap.put("code_url", resultMap.get("code_url"));
            returnMap.put("course_id", order.getCourseId());
            returnMap.put("total_fee", order.getTotalFee());
            returnMap.put("out_trade_no", orderNo);
            return returnMap;

        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new MyException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
    }
}
